const express = require('express');
const { query } = require('../config/database-sqlite');
const { optionalAuth } = require('../middleware/auth');

const router = express.Router();

// 综合搜索
router.get('/', optionalAuth, async (req, res) => {
  try {
    const { keyword, type = 'all', page = 1, limit = 20 } = req.query;
    
    if (!keyword || keyword.trim().length === 0) {
      return res.status(400).json({ error: '搜索关键词不能为空' });
    }

    const searchKeyword = `%${keyword.trim()}%`;
    const offset = (page - 1) * limit;
    const results = {};

    // 搜索歌曲
    if (type === 'all' || type === 'songs') {
      const songs = await query(`
        SELECT s.*, a.name as artist_name
        FROM songs s
        LEFT JOIN artists a ON s.artist_id = a.id
        WHERE s.status = 1 AND (s.name LIKE ? OR a.name LIKE ?)
        ORDER BY s.play_count DESC, s.created_at DESC
        LIMIT ? OFFSET ?
      `, [searchKeyword, searchKeyword, parseInt(limit), parseInt(offset)]);

      // 如果用户已登录，检查收藏状态
      if (req.user && songs.length > 0) {
        const songIds = songs.map(song => song.id);
        const favorites = await query(
          `SELECT song_id FROM user_favorites WHERE user_id = ? AND song_id IN (${songIds.map(() => '?').join(',')})`,
          [req.user.id, ...songIds]
        );
        const favoriteIds = new Set(favorites.map(f => f.song_id));
        
        songs.forEach(song => {
          song.is_favorited = favoriteIds.has(song.id);
        });
      }

      results.songs = songs;
    }

    // 搜索歌手
    if (type === 'all' || type === 'artists') {
      const artists = await query(`
        SELECT a.*, 
               (SELECT COUNT(*) FROM songs s WHERE s.artist_id = a.id AND s.status = 1) as song_count
        FROM artists a
        WHERE a.status = 1 AND a.name LIKE ?
        ORDER BY song_count DESC, a.created_at DESC
        LIMIT ? OFFSET ?
      `, [searchKeyword, parseInt(limit), parseInt(offset)]);

      results.artists = artists;
    }

    // 搜索专辑
    if (type === 'all' || type === 'albums') {
      const albums = await query(`
        SELECT al.*, a.name as artist_name,
               (SELECT COUNT(*) FROM songs s WHERE s.album_id = al.id AND s.status = 1) as song_count
        FROM albums al
        LEFT JOIN artists a ON al.artist_id = a.id
        WHERE al.status = 1 AND al.name LIKE ?
        ORDER BY song_count DESC, al.created_at DESC
        LIMIT ? OFFSET ?
      `, [searchKeyword, parseInt(limit), parseInt(offset)]);

      results.albums = albums;
    }

    // 搜索歌单
    if (type === 'all' || type === 'playlists') {
      const playlists = await query(`
        SELECT p.*, u.nickname as creator_name,
               (SELECT COUNT(*) FROM playlist_songs ps WHERE ps.playlist_id = p.id) as song_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.status = 1 AND p.is_public = 1 AND (p.name LIKE ? OR p.description LIKE ?)
        ORDER BY p.like_count DESC, p.created_at DESC
        LIMIT ? OFFSET ?
      `, [searchKeyword, searchKeyword, parseInt(limit), parseInt(offset)]);

      results.playlists = playlists;
    }

    res.json({
      keyword: keyword.trim(),
      results,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });

  } catch (error) {
    console.error('搜索错误:', error);
    res.status(500).json({ error: '搜索失败' });
  }
});

// 搜索建议
router.get('/suggest', async (req, res) => {
  try {
    const { keyword } = req.query;
    
    if (!keyword || keyword.trim().length === 0) {
      return res.json({ suggestions: [] });
    }

    const searchKeyword = `${keyword.trim()}%`;
    const suggestions = [];

    // 获取歌曲建议
    const songs = await query(`
      SELECT DISTINCT s.name
      FROM songs s
      WHERE s.status = 1 AND s.name LIKE ?
      ORDER BY s.play_count DESC
      LIMIT 5
    `, [searchKeyword]);

    suggestions.push(...songs.map(s => ({ type: 'song', text: s.name })));

    // 获取歌手建议
    const artists = await query(`
      SELECT DISTINCT a.name
      FROM artists a
      WHERE a.status = 1 AND a.name LIKE ?
      ORDER BY a.created_at DESC
      LIMIT 5
    `, [searchKeyword]);

    suggestions.push(...artists.map(a => ({ type: 'artist', text: a.name })));

    // 限制总建议数量
    const limitedSuggestions = suggestions.slice(0, 8);

    res.json({ suggestions: limitedSuggestions });

  } catch (error) {
    console.error('获取搜索建议错误:', error);
    res.status(500).json({ error: '获取搜索建议失败' });
  }
});

// 热门搜索
router.get('/hot', async (req, res) => {
  try {
    // 这里可以根据实际需求实现热门搜索词的逻辑
    // 目前返回静态数据
    const hotKeywords = [
      '周杰伦', '陈奕迅', '邓丽君', '稻香', '青花瓷', 
      '孤勇者', '晴天', '夜曲', '告白气球', '简单爱'
    ];

    res.json({ hotKeywords });

  } catch (error) {
    console.error('获取热门搜索错误:', error);
    res.status(500).json({ error: '获取热门搜索失败' });
  }
});

module.exports = router;